import { createRouter, createWebHistory } from "vue-router";
import { useUserStore } from "@/stores/user";

// 静态路由
import MainLayout from "@/views/layouts/MainLayout.vue";
import Course from "@/views/Course.vue";
import Login from "@/views/Login.vue";
import CourseDetails from "@/views/CourseDetails.vue";

const router = createRouter({
  history: createWebHistory(),
  routes: [
    {
      path: "/",
      name: "index",
      component: MainLayout,
      redirect: { name: "home" },
      children: [
        {
          path: "home",
          name: "home",
          component: Course,
          meta: {
            title: "课程信息",
            requireAuth: true,
          },
        },
        {
          path: "course/:id",
          name: "course",
          component: CourseDetails,
          props: true,
          meta: {
            title: "实训报告",
            requireAuth: true,
          },
        },
        {
          path: "profile",
          name: "profile",
          component: () => import("@/views/Profile.vue"),
          meta: {
            title: "个人信息",
            requireAuth: true,
          },
        },
      ],
    },
    {
      path: "/login",
      name: "login",
      component: Login,
      meta: {
        title: "登录",
      },
    },
  ],
});

// 路由守卫
router.beforeEach((to) => {
  // 设置页面标题
  document.title = `${to.meta.title} - 实训报告管理系统`;
  // 权限验证
  if (to.meta.requireAuth) {
    const userStore = useUserStore();
    if (!userStore.isLogin()) {
      return { name: "login" };
    }
  }
});

export default router;
